package com.nsgf.library.widget;

import static androidx.core.content.res.TypedArrayUtils.getText;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

 public class JustifiedTextView extends TextView {

    private String originalText;
    private boolean isJustified = false;

    public JustifiedTextView(Context context) {
        super(context);
        init();
    }

    public JustifiedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public JustifiedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 保存原始文本
        originalText = getText().toString();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w > 0 && !isJustified) {
            justifyText();
        }
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text.toString();
        isJustified = false;
        super.setText(text, type);
    }

    private void justifyText() {
        if (TextUtils.isEmpty(originalText) || getWidth() <= 0) {
            return;
        }

        Paint paint = getPaint();
        paint.setTextSize(getTextSize());

        // 计算可用宽度（减去padding）
        int availableWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        // 分行处理文本
        String[] words = originalText.split("\\s+");
        StringBuilder justifiedText = new StringBuilder();
        StringBuilder currentLine = new StringBuilder();

        for (String word : words) {
            String testLine = currentLine.toString() + (currentLine.length() > 0 ? " " : "") + word;
            float lineWidth = paint.measureText(testLine);

            if (lineWidth <= availableWidth) {
                // 单词可以添加到当前行
                currentLine.append(currentLine.length() > 0 ? " " : "").append(word);
            } else {
                // 当前行已满，需要处理当前行并开始新行
                if (currentLine.length() > 0) {
                    justifiedText.append(justifyLine(currentLine.toString(), availableWidth, paint));
                    justifiedText.append("\n");
                }
                currentLine = new StringBuilder(word);
            }
        }

        // 处理最后一行
        if (currentLine.length() > 0) {
            justifiedText.append(currentLine.toString());
        }

        // 设置处理后的文本
        isJustified = true;
        super.setText(justifiedText.toString(), BufferType.NORMAL);
    }

    private String justifyLine(String line, int width, Paint paint) {
        if (line.length() <= 1) {
            return line;
        }

        // 计算当前行的宽度
        float lineWidth = paint.measureText(line);
        float extraSpace = width - lineWidth;

        if (extraSpace <= 0) {
            return line;
        }

        // 计算单词间的空格数量
        String[] words = line.split("\\s+");
        if (words.length <= 1) {
            return line;
        }

        // 计算每个空格需要增加的空间
        float spacePerGap = extraSpace / (words.length - 1);
        float singleSpaceWidth = paint.measureText(" ");

        StringBuilder justifiedLine = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            justifiedLine.append(words[i]);

            if (i < words.length - 1) {
                // 添加原始空格
                justifiedLine.append(" ");

                // 添加额外的空格
                int extraSpaces = Math.round(spacePerGap / singleSpaceWidth);
                for (int j = 0; j < extraSpaces; j++) {
                    justifiedLine.append(" ");
                }
            }
        }

        return justifiedLine.toString();
    }
}